package service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import service.oss.service.OssService;
import service.oss.utils.ConstantProperties;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //配置OSS参数
        String endpoint = ConstantProperties.END_POINT;
        String keyId = ConstantProperties.KEY_ID;
        String keySecret = ConstantProperties.KEY_SECRET;
        String bucketName = ConstantProperties.BUCKET_NAME;
        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            //获取上传文件输入流
            InputStream fileInputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //防止上传文件名重复导致替换原有文件,使用uuid
            String s = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=s+"_"+fileName;
            //将文件按照日期进行分类
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            fileName=dataPath+"/"+fileName;//必须加/才能生成日期文件夹进行自动分类
            //调用OSS方法实现上传
            ossClient.putObject(bucketName, fileName, fileInputStream);
            //关闭OSS
            ossClient.shutdown();
            //返回路径
            return "https://" + bucketName + "." + endpoint + "/" + fileName;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
